﻿using AntdUI;
using CKS.AGV.Server.ViewModel;
using CKS.Core.Framework;
using CKS.Core.Framework.Models;
using CKS.Models;
using FreeSql;
using Mapster;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CKS.AGV.Server.Controls
{
    /// <summary>
    /// 配置小车坐标-通信点位
    /// </summary>
    public partial class PathPointTable : UserControl
    {
        IFreeSql<MesDB> fsql;
        IBaseRepository<agv_path_point> repoPoint;
        public PathPointTable()
        {
            InitializeComponent();

            this.Load += TasksTable_Load;

        }

        private void TasksTable_Load(object sender, EventArgs e)
        {
            try
            {
                InitTable();
                if (DesignMode)
                    return;
                fsql = AppCache.GetServiceProvider().GetService<IFreeSql<MesDB>>();
                repoPoint = fsql.GetRepository<agv_path_point>();
                Run();
            }
            catch (Exception)
            {

            }

        }

        private void InitTable()
        {
            table1.EditMode = TEditMode.None;
            table1.Columns = new ColumnCollection();


            table1.Columns.Add(new Column("Remark", "备注") { Fixed = true, Style = new Table.CellStyleInfo() { BackColor = Color.Yellow, ForeColor = Color.Black } });
            // table1.Columns.Add(new Column("TaskType", "任务类型") { Fixed = true, Style = new Table.CellStyleInfo() { BackColor = Color.Yellow, ForeColor = Color.Black } });

            table1.Columns.Add(new Column("StationId", "工站Id") { Fixed = true, Style = new Table.CellStyleInfo() { BackColor = Color.Yellow, ForeColor = Color.Black } });
            table1.Columns.Add(new Column("StationArea", "区域") { Fixed = true, Style = new Table.CellStyleInfo() { BackColor = Color.Yellow, ForeColor = Color.Black } });
            table1.Columns.Add(new Column("Point", "地图坐标") { Fixed = true, Style = new Table.CellStyleInfo() { BackColor = Color.Yellow, ForeColor = Color.Black } });

            table1.Columns.Add(new Column("PointTypeCellText", "坐标类型") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            table1.Columns.Add(new Column("AgvModbusAddr", "agv-信号地址") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            table1.Columns.Add(new Column("UpperModbusAddr", "upper-信号地址") { Fixed = true, Style = new Table.CellStyleInfo() { } });

            table1.Bordered = true;
            table1.EnableHeaderResizing = true;
            table1.EmptyHeader = true;
            table1.Gap = 6;
            table1.VisibleHeader = true;
            table1.ClipboardCopy = false;

            table1.CellClick += Table1_CellClick;
        }

        private void Table1_CellClick(object sender, TableClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                var col = table1.Columns[e.ColumnIndex];
                switch (col.Key)
                {
                    case "PointTypeCellText":
                        break;
                    default:
                        table1.EnterEditMode(e.RowIndex, e.ColumnIndex);
                        break;
                }

            }
            else if(e.Button == MouseButtons.Right)
            {
                var data = e.Record as View_path_point;
                var index = points.IndexOf(data);
                var indexId = index + 1;
                if (index == -1 || points.Count == 0)
                    return;
                List<IContextMenuStripItem> menus = new List<IContextMenuStripItem>();
                menus.Add(new ContextMenuStripItem("上方插入1行") { ID = "add" });
                menus.Add(new ContextMenuStripItem("删除"){ ID = "delete"});
                AntdUI.ContextMenuStrip.open(table1, OnClickRightMenu(data), menus.ToArray());
            }

        }

        private Action<ContextMenuStripItem> OnClickRightMenu(View_path_point data)
        {
            var index = points.IndexOf(data);
            Action<ContextMenuStripItem> action = (menu) =>
            {
                switch (menu.ID)
                {
                    case "add":
                        AddRows(index);
                        break;
                    case "delete":
                        points.Remove(data);
                        repoPoint.Delete(data.Adapt<agv_path_point>());
                       
                        break;
                  
                    
                    default:
                        break;
                }
            };
            return action;
        }

        AntList<View_path_point> points = new AntList<View_path_point>();

        public void Query()
        {

            var ls = repoPoint.Select
                       .OrderBy(a => new { a.StationId, a.StationArea,a.PointType })
                       .ToList();
            points = ls.Adapt<AntList<View_path_point>>();
            table1.Binding(points);
        }


        public void Run() // 每秒刷新一次任务列表
        {

            try
            {
                Query();


            }
            catch (Exception)
            {

            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddRows();
        }

        private void AddRows(int index = -1)
        {

            var row = new View_path_point()
            {
                CreatedTime = DateTime.Now,
                Remark = "",
                UpdateTime = DateTime.Now,
            };



            if (index > -1)
            {
                points.Insert(index, row);
            }
            else
                points.Add(row);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (points.Count <= 0)
                return;



            foreach (var point in points)
            {
                //

                var model = point.Adapt<agv_path_point>();



                if (model.Id == 0)
                {
                    repoPoint.Insert(model);
                }
                else
                {
                    repoPoint.Update(model);
                }
            }
            Query();

            MessageBoxShow("保存成功");
        }
        public void MessageBoxShow(string message, TType type = TType.Info)
        {
            try
            {
                AntdUI.Modal.open(new AntdUI.Modal.Config(this.FindForm(), "消息", message)
                {
                    Icon = type,
                    //内边距
                    Padding = new Size(24, 20),
                    OkText = "确认",
                    CancelText = null,
                });
            }
            catch (Exception)
            {

            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            Query();
        }
    }
}

